<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="JS方法&#x2F;函数重载的姿势JavaScript不支持重载的语法，它没有重载所需要的函数签名。  ECMAScript函数不能像传统意义上那样实现重载。而在其他语言（如 Java）中，可以为一个函数编写两个定义，只要这两个定义的签名（接受的参数的类型和数量）不同即可。如前所述，ECMAScirpt函数没有签名，因为其参数是由包含零或多个值的数组来表示的。而没有函数签名，真正的重载是不可能做到的。 —">
<meta property="og:type" content="article">
<meta property="og:title" content="深入探究JavaScript">
<meta property="og:url" content="http://example.com/2020/09/06/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="JS方法&#x2F;函数重载的姿势JavaScript不支持重载的语法，它没有重载所需要的函数签名。  ECMAScript函数不能像传统意义上那样实现重载。而在其他语言（如 Java）中，可以为一个函数编写两个定义，只要这两个定义的签名（接受的参数的类型和数量）不同即可。如前所述，ECMAScirpt函数没有签名，因为其参数是由包含零或多个值的数组来表示的。而没有函数签名，真正的重载是不可能做到的。 —">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript.assets/1044137-20170831143725077-1955052959.png">
<meta property="og:image" content="http://example.com/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript.assets/1760011-20200512143232426-796587478.png">
<meta property="og:image" content="http://example.com/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript.assets/1760011-20200512143348561-1197833870.png">
<meta property="article:published_time" content="2020-09-06T13:28:16.000Z">
<meta property="article:modified_time" content="2021-11-03T08:32:20.704Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="面试总结">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript.assets/1044137-20170831143725077-1955052959.png">

<link rel="canonical" href="http://example.com/2020/09/06/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>深入探究JavaScript | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2020/09/06/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          深入探究JavaScript
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2020-09-06 21:28:16" itemprop="dateCreated datePublished" datetime="2020-09-06T21:28:16+08:00">2020-09-06</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:32:20" itemprop="dateModified" datetime="2021-11-03T16:32:20+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/" itemprop="url" rel="index"><span itemprop="name">面试总结</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="JS方法-函数重载的姿势"><a href="#JS方法-函数重载的姿势" class="headerlink" title="JS方法/函数重载的姿势"></a>JS方法/函数重载的姿势</h1><p>JavaScript不支持重载的语法，它没有重载所需要的函数签名。</p>
<blockquote>
<p>ECMAScript函数不能像传统意义上那样实现重载。而在其他语言（如 Java）中，可以为一个函数编写两个定义，只要这两个定义的签名（接受的参数的类型和数量）不同即可。如前所述，<strong>ECMAScirpt函数没有签名</strong>，因为其参数是由包含零或多个值的数组来表示的。而<strong>没有函数签名，真正的重载是不可能做到的</strong>。 — <em>JavaScript高级程序设计（第3版）3.7.2小节</em></p>
</blockquote>
<p>在JavaScript中，函数名本身就是变量，函数声明类似于变量赋值。当同个函数名被多次声明时，后声明的内容将覆盖前面的内容。尽管JavaScript无法做到真正的重载，但是可以通过检查传入函数中参数的类型和数量并作相应的处理，从而实现重载的效果，曲线救国。</p>
<h2 id="借助流程控制语句"><a href="#借助流程控制语句" class="headerlink" title="借助流程控制语句"></a>借助流程控制语句</h2><p>通过判断传入参数的数量（arguments.length），执行相应的代码块。</p>
<h2 id="巧用闭包特性"><a href="#巧用闭包特性" class="headerlink" title="巧用闭包特性"></a>巧用闭包特性</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> ninja = &#123;&#125;;</span><br><span class="line">addMethod(ninja, <span class="string">'whatever'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;<span class="comment">/* code */</span>&#125;);</span><br><span class="line">addMethod(ninja, <span class="string">'whatever'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">a</span>)</span>&#123;<span class="comment">/* code */</span>&#125;);</span><br><span class="line">addMethod(ninja, <span class="string">'whatever'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">a,b</span>)</span>&#123;<span class="comment">/* code */</span>&#125;);</span><br></pre></td></tr></table></figure>

<p>addMethod函数接收3个参数：目标对象、目标方法名、函数体，当函数被调用时：</p>
<p>先将目标object[name]的值存入变量old中，因此<strong>起初old中的值可能不是一个函数</strong>；接着向object[name]赋值一个代理函数，并且由于变量old、fn在代理函数中被引用，所以<strong>old、fn将常驻内存</strong>不被回收。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">addMethod</span>(<span class="params">object, name, fn</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> old = object[name];  <span class="comment">// 保存前一个值，以便后续调用</span></span><br><span class="line">  object[name] = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;  <span class="comment">// 向object[name]赋值一个代理函数</span></span><br><span class="line">    <span class="comment">// 判断fn期望接收的参数与传入参数个数是否一致</span></span><br><span class="line">    <span class="keyword">if</span> (fn.length == <span class="built_in">arguments</span>.length)</span><br><span class="line">      <span class="comment">// 若是，则调用fn</span></span><br><span class="line">      <span class="keyword">return</span> fn.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>)</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> old == <span class="string">'function'</span>)  <span class="comment">// 若否，则判断old的值是否为函数</span></span><br><span class="line">      <span class="comment">// 若是，则调用old</span></span><br><span class="line">      <span class="keyword">return</span> old.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>代理函数被调用时：</p>
<p>先判断传入参数与<strong>其父级作用域中fn</strong>期望接收参数的个数是否一致，若是则调用该fn；</p>
<p>若否，则判断<strong>其父级作用域中old</strong>值类型是否为函数，若是则调用该old；</p>
<p> 当old中存有上一次生成的代理函数时，则会重复前面两个步骤，直至old值<strong>不为代理函数</strong>。</p>
<hr>
<p>上述两种方法都是通过检查参数个数来实现重载，<strong>不区分参数类型</strong>。此外，方法1在继承时重载的那些函数无法被重写，而方法2通过逐个执行代理函数，比对参数个数，直至找到目标函数，效率不高。</p>
<h2 id="巧用引用类型特性"><a href="#巧用引用类型特性" class="headerlink" title="巧用引用类型特性"></a>巧用引用类型特性</h2><p><strong>核心思想</strong>：由于ECMAScript函数是一种<strong>引用类型</strong>对象，可扩展属性与方法。借此通过创建一个容器用于存储要重载的函数，并将容器挂载到代理函数上以便后续访问，而代理函数利用闭包特性访问容器。</p>
<p><strong>重载顺序</strong>：首先查找参数类型匹配的函数，其次查找参数个数匹配的函数。</p>
<p><strong>存储格式</strong>：键值对，键名由逗号与参数个数或参数类型组成，键值为要重载的函数，如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">',0'</span>: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;<span class="comment">/* code */</span>&#125;,</span><br><span class="line">  <span class="string">',1'</span>: <span class="function"><span class="keyword">function</span>(<span class="params">a</span>)</span>&#123;<span class="comment">/* code */</span>&#125;,</span><br><span class="line">  <span class="string">',string,number'</span>: <span class="function"><span class="keyword">function</span>(<span class="params">a,b</span>)</span>&#123;<span class="comment">/* code */</span>&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>工具函数被调用时</strong>：</p>
<ol>
<li>先判断是否已重载过，若有，直接将要重载的函数按格式存入容器；</li>
<li>若未重载过，则创建一个容器变量；</li>
<li> 判断未重载前的值是否为一个函数，若是，则以逗号+参数个数的格式存入容器；</li>
<li>将要重载的函数存入容器；</li>
<li>代理原函数，并将容器挂载到代理函数上；</li>
<li>当代理函数被调用时，将依次查找容器中匹配的函数并调用。</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 重载工具函数</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Object&#125;</span> <span class="variable">ctx</span></span> - 上下文</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;String&#125;</span> <span class="variable">name</span></span> - 函数名</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Function&#125;</span> <span class="variable">fn</span></span> - 函数体</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;String&#125;</span> <span class="variable">type</span></span> - 参数类型</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author </span>范围兄 &lt;ambit_tsai<span class="doctag">@qq</span>.com&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@example </span>不指定参数类型</span></span><br><span class="line"><span class="comment"> *  overload(obj, 'do', function()&#123;...&#125;);</span></span><br><span class="line"><span class="comment"> *  overload(obj, 'do', function(a)&#123;...&#125;);</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@example </span>指定参数类型</span></span><br><span class="line"><span class="comment"> *  overload(obj, 'do', function(a,b)&#123;...&#125;, 'string,number');</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">overload</span>(<span class="params">ctx, name, fn, type</span>)</span>&#123;</span><br><span class="line">  type = type? type.trim().toLowerCase(): fn.length;</span><br><span class="line">  <span class="comment">// 已重载过</span></span><br><span class="line">  <span class="keyword">if</span>(<span class="keyword">typeof</span> ctx[name]===<span class="string">'function'</span> &amp;&amp; <span class="keyword">typeof</span> ctx[name]._$fnMap===<span class="string">'object'</span>)&#123;</span><br><span class="line">    ctx[name]._$fnMap[<span class="string">','</span>+type] = fn;	<span class="comment">// 将fn存入_$fnMap</span></span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 未重载过</span></span><br><span class="line">  <span class="keyword">var</span> fnMap = &#123;&#125;;   <span class="comment">// 容器</span></span><br><span class="line">  <span class="keyword">if</span>(<span class="keyword">typeof</span> ctx[name] === <span class="string">'function'</span>)&#123;</span><br><span class="line">    <span class="comment">// 若ctx[name]是一个函数，则存入容器</span></span><br><span class="line">    fnMap[<span class="string">','</span>+ctx[name].length] = ctx[name];</span><br><span class="line">  &#125;</span><br><span class="line">  fnMap[<span class="string">','</span>+type] = fn;</span><br><span class="line">  ctx[name] = <span class="function"><span class="keyword">function</span> <span class="title">overloading</span>(<span class="params"></span>)</span>&#123;   <span class="comment">// 代理</span></span><br><span class="line">    <span class="keyword">var</span> args = <span class="built_in">arguments</span>, </span><br><span class="line">        len = args.length, </span><br><span class="line">        type, i;</span><br><span class="line">    <span class="keyword">for</span>(i=<span class="number">0</span>, type=<span class="string">''</span>; i&lt;len; ++i)&#123;  <span class="comment">// 计算参数类型</span></span><br><span class="line">      type += <span class="string">','</span> + <span class="keyword">typeof</span> args[i];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 依次匹配：参数类型-&gt;参数个数</span></span><br><span class="line">    <span class="keyword">if</span>(fnMap[type]) <span class="keyword">return</span> fnMap[type].apply(<span class="keyword">this</span>, args);</span><br><span class="line">    <span class="keyword">if</span>(fnMap[<span class="string">','</span>+len]) <span class="keyword">return</span> fnMap[<span class="string">','</span>+len].apply(<span class="keyword">this</span>, args);</span><br><span class="line">    <span class="keyword">throw</span> <span class="string">'Overload: no matched function'</span>;</span><br><span class="line">  &#125;;</span><br><span class="line">  ctx[name]._$fnMap = fnMap;   <span class="comment">// 将fnMap挂载到代理上</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="JS异步操作的方法"><a href="#JS异步操作的方法" class="headerlink" title="JS异步操作的方法"></a>JS异步操作的方法</h1><h2 id="回调函数"><a href="#回调函数" class="headerlink" title="回调函数"></a>回调函数</h2><p><strong>回调函数是异步编程中最基本的方法</strong>。假设有<strong>三个函数f1、f2、f3</strong>，<strong>f2需要等待f1</strong>的执行结果，<strong>而f3是独立的，不需要f1和f2的结果</strong>，如果我们写成同步，就是这样的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">　　f1();</span><br><span class="line">　　f2();　　f3()</span><br></pre></td></tr></table></figure>

<p>如果f1执行的很快，可以； 但是如果f1执行的很慢，那么f2和f3就会被阻塞，无法执行。这样的效率是非常低的。但是<strong>我们可以改写，将f2写成是f1的回调函数，如下：</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">　　<span class="function"><span class="keyword">function</span> <span class="title">f1</span>(<span class="params">callback</span>)</span>&#123;</span><br><span class="line">　　　　setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">　　　　　　<span class="comment">// f1的任务代码</span></span><br><span class="line">　　　　　　callback();</span><br><span class="line">　　　　&#125;, <span class="number">1000</span>);</span><br><span class="line">　　&#125;</span><br></pre></td></tr></table></figure>

<p>　那么这时候执行代码就是这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">f1(f2);</span><br><span class="line">f3()</span><br></pre></td></tr></table></figure>

<p>这样，就是一个异步的执行了，即使f1很费时间，但是<strong>由于是异步的，那么f3()就会很快的得到执行，而不会受到f1和f2的影响。</strong></p>
<p><strong>注意： 如果我们把f1写成这样呢？</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f1</span>(<span class="params">callback</span>)</span>&#123;</span><br><span class="line">　　<span class="comment">// f1的任务代码</span></span><br><span class="line">　　callback();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后，我们同样可以这么调用：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">f1(f2);</span><br><span class="line">f3()</span><br></pre></td></tr></table></figure>

<p><strong>这时候还是异步的吗？</strong> <strong>答案：不是异步。</strong> 这里的回调函数并非真正的回调函数，如果没有利用setTimeout含函数，那么f3()的执行同样需要等到f1(f2)完全执行完毕，<strong>这里要注意</strong>。而我们就是利用setTImeout才能做出真正的回调函数。</p>
<h2 id="事件监听"><a href="#事件监听" class="headerlink" title="事件监听"></a>事件监听</h2><p>另一种异步的思路是采用事件驱动模式。任务的执行不取决于代码的顺序， 而取决于某个事件是否发生。 还是以f1、f2、f3为例子。 首先，<strong>为f1绑定一个事件</strong>（这里采用jquery的写法）：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">f1.on(<span class="string">'done'</span>, f2);</span><br><span class="line">f3()</span><br></pre></td></tr></table></figure>

<p>这里的意思是： 当f1发生了done事件，就执行f2， 然后，我们对f1进行改写：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">　　<span class="function"><span class="keyword">function</span> <span class="title">f1</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">　　　　setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">　　　　　　<span class="comment">// f1的任务代码</span></span><br><span class="line">　　　　　　f1.trigger(<span class="string">'done'</span>);</span><br><span class="line">　　　　&#125;, <span class="number">1000</span>);</span><br><span class="line">　　&#125;</span><br></pre></td></tr></table></figure>

<p>f1.trigger(‘done’)表示， 执行完成后，立即触发done事件，从而开始执行f2。</p>
<p><strong>这种方法的优点</strong>就是比较容易理解，可以绑定多个事件，每个事件可以指定多个回调函数，而且可以去耦合，有利于实现模块化<strong>，缺点就是整个程序都要变成事件驱动型，运行流程会变得很不清晰。</strong></p>
<h2 id="发布订阅"><a href="#发布订阅" class="headerlink" title="发布订阅"></a>发布订阅</h2><p>第二种方法的事件，实际上我们完全可以理解为“信号”，即f1完成之后，触发了一个 ‘done’，信号，然后再开始执行f2。</p>
<p><strong>我们假定，存在一个“信号中心”，某个任务执行完成，就向信号中心“发布”（publish）一个信号，其他任务可以向信号中心“订阅”这个信号， 从而知道什么时候自己可以开始执行。 这个就叫做“发布/订阅模式”， 又称为“观察者”模式 。</strong> </p>
<p>这个模式有多种实现， 下面采用Ben Alman的Tiny PUb/Sub，这是jQuery的一个插件。</p>
<p>首先，<strong>f2向”信号中心”jquery订阅”done”信号，</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jQuery.subscribe(<span class="string">"done"</span>, f2);</span><br></pre></td></tr></table></figure>

<p>然后，f1进行如下改写：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">　　<span class="function"><span class="keyword">function</span> <span class="title">f1</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">　　　　setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">　　　　　　<span class="comment">// f1的任务代码</span></span><br><span class="line">　　　　　　jQuery.publish(<span class="string">"done"</span>);</span><br><span class="line">　　　　&#125;, <span class="number">1000</span>);</span><br><span class="line">　　&#125;</span><br></pre></td></tr></table></figure>

<p><strong>jquery.pushlish(“done”)的意思是： f1执行完成后，向“信号中心”jQuery发布“done”信号，从而引发f2的执行。</strong> </p>
<p>此外，f2完成执行后，也可以取消订阅（unsubscribe）。</p>
<p>　　</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">　jQuery.unsubscribe(<span class="string">"done"</span>, f2);</span><br></pre></td></tr></table></figure>

<p>这种方法的性质和“事件监听”非常类似，但是明显是优于前者的，<strong>因为我们可以通过查看“消息中心”，了解到存在多少信号、每个信号有多少个订阅者，从而监控程序的运行。</strong></p>
<h2 id="promise对象"><a href="#promise对象" class="headerlink" title="promise对象"></a>promise对象</h2><p>promise是commonjs工作组提出来的一种规范，<strong>目的是为异步编程提供统一接口。</strong></p>
<p>简答的说，它的思想是每一个异步任务返回一个promise对象，该对象有一个then方法，允许指定回调函数。 比如,f1的回调函数f2，可以写成：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">f1().then(f2);</span><br></pre></td></tr></table></figure>

<p>f1要进行下面的改写（这里使用jQuery的实现）：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">　<span class="function"><span class="keyword">function</span> <span class="title">f1</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">　　　　<span class="keyword">var</span> dfd = $.Deferred();</span><br><span class="line">　　　　setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">　　　　　　<span class="comment">// f1的任务代码</span></span><br><span class="line">　　　　　　dfd.resolve();</span><br><span class="line">　　　　&#125;, <span class="number">500</span>);</span><br><span class="line">　　　　<span class="keyword">return</span> dfd.promise;</span><br><span class="line">　　&#125;</span><br></pre></td></tr></table></figure>

<p>这样的优点在于，<strong>回调函数编程了链式写法，程序的流程可以看得很清楚，而且有一整套的配套方法，可以实现很多强大的功能 。</strong></p>
<p>如：指定多个回调函数：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">　f1().then(f2).then(f3);</span><br></pre></td></tr></table></figure>

<p>再比如，指定发生错误时的回调函数：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">f1().then(f2).fail(f3);</span><br></pre></td></tr></table></figure>

<p>而且，他还有一个前面三种方法都没有的好处：如果一个任务已经完成，再添加回调函数，该回调函数会立即执行。　所以，你不用担心是否错过了某个事件或者信号，<strong>这种方法的确定就是编写和理解，都比较困难。</strong></p>
<h2 id="generator函数的异步应用"><a href="#generator函数的异步应用" class="headerlink" title="generator函数的异步应用"></a>generator函数的异步应用</h2><p>而<strong>generator函数将JavaScript异步编程带入了一个全新的阶段！</strong></p>
<p>比如，有一个任务是读取文件进行处理，任务的第一段是向操作系统发出请求，要求读取文件。然后，<strong>程序执行其他任务</strong>，等到操作系统返回文件，再<strong>接着执行</strong>任务的第二段（处理文件）。<strong>这种不连续的执行，就叫做异步。</strong></p>
<p>相应地，连续的执行就叫做同步。由于是连续执行，不能插入其他任务，所以操作系统从硬盘读取文件的这段时间，程序只能干等着<strong>。</strong></p>
<p>　　  </p>
<p><strong>协程</strong></p>
<p>　传统的编程语言中，早就有了异步编程的解决方案，<strong>其中一种叫做协程</strong>，意思是多个线程互相协作，<strong>完成异步任务</strong>。</p>
<p>　　协程优点像函数，又有点像线程，运行流程如下：</p>
<ul>
<li>第一步，协程<code>A</code>开始执行。</li>
<li>第二步，协程<code>A</code>执行到一半，<strong>进入暂停</strong>，<strong>执行权转移</strong>到协程<code>B</code>。</li>
<li>第三步，（一段时间后）协程<code>B</code><strong>交还执行权</strong>。</li>
<li>第四步，协程<code>A</code><strong>恢复执行</strong>。</li>
</ul>
<p>　　<strong>上面的协程A，就是异步任务，因为它分为两段（或者多段）执行。</strong> </p>
<p>　　举例来说，读取文件的协程写法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">function *asyncJob() &#123;</span><br><span class="line">  &#x2F;&#x2F; ...其他代码</span><br><span class="line">  var f &#x3D; yield readFile(fileA);</span><br><span class="line">  &#x2F;&#x2F; ...其他代码</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>　　上面代码的函数asyncJob是一个协程，<strong>奥妙就在于yield命令，</strong> 它表示执行到此处，<strong>执行权交给其他协程</strong>，也就是说<strong>yield命令是异步两个阶段的分界线。</strong> </p>
<p>　　协程遇到yield命令就暂停，等到执行权返回，再从暂停的地方继续向后执行，它的最大优点就是<strong>代码的写法非常像同步操作</strong>，如果去除yield命令，简直是一模一样。</p>
<p><strong>协程的Generator函数实现</strong></p>
<p>　　Generator函数是协程在ES6中的实现，<strong>最大特点就是可以交出函数的执行权（即暂停执行）。</strong></p>
<p>　　整个<strong>Generator函数就是一个封装的异步任务</strong>，或者说异步任务的容器。 异步任务需要暂停的地方，都用yield语句注明。 如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function* gen(x) &#123;</span><br><span class="line">  var y &#x3D; yield x + 2;</span><br><span class="line">  return y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var g &#x3D; gen(1);</span><br><span class="line">g.next() &#x2F;&#x2F; &#123; value: 3, done: false &#125;</span><br><span class="line">g.next() &#x2F;&#x2F; &#123; value: undefined, done: true &#125;</span><br></pre></td></tr></table></figure>

<p>　　在调用gen函数时 gen(1)， 会<strong>返回一个内部指针（即遍历器）g。</strong> 这是Generator函数不同于普通函数的另一个地方，<strong>即执行它（调用函数）不会返回结果</strong>， 返回的一个指针对象 。<strong>调用指针g的next方法，会移动内部指针（即执行异步任务的第一阶段），指向第一个遇到的yield语句，</strong>这里我们是x + 2，但是实际上这里只是举例，实际上 x + 2 这句应该是一个异步操作，比如ajax请求。 <strong>换言之，next</strong>方法的作用是分阶段执行Generator函数。每次调用next方法，会返回一个对象，表示当前阶段的信息（value属性和done属性）。 value属性是yield语句后面表达式的值，表示当前阶段的值；done属性是一个布尔值，表示Generator函数是否执行完毕，即是否还有下一个阶段。</p>
<p><strong>Generator函数的数据交换和错误处理</strong></p>
<p>　　Generator 函数可以暂停执行和恢复执行，这是它能封装异步任务的根本原因。除此之外，它还有两个特性，使它可以作为异步编程的完整解决方案：函数体内外的数据交换和错误处理机制。</p>
<p>　　<code>next</code>返回值的value属性，是 Generator 函数向外输出数据；<code>next</code>方法还可以接受参数，向 Generator 函数体内输入数据。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function* gen(x)&#123;</span><br><span class="line">  var y &#x3D; yield x + 2;</span><br><span class="line">  return y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var g &#x3D; gen(1);</span><br><span class="line">g.next() &#x2F;&#x2F; &#123; value: 3, done: false &#125;</span><br><span class="line">g.next(2) &#x2F;&#x2F; &#123; value: 2, done: true &#125;</span><br></pre></td></tr></table></figure>

<p>　　上面代码中，第一<code>next</code>方法的<code>value</code>属性，返回表达式<code>x + 2</code>的值<code>3</code>。第二个<code>next</code>方法带有参数<code>2</code>，这个参数可以传入 Generator 函数，作为上个阶段异步任务的返回结果，被函数体内的变量<code>y</code>接收。因此，这一步的<code>value</code>属性，返回的就是<code>2</code>（变量<code>y</code>的值）。</p>
<p>Generator 函数内部还可以部署错误处理代码，捕获函数体外抛出的错误。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">function* gen(x)&#123;</span><br><span class="line">  try &#123;</span><br><span class="line">    var y &#x3D; yield x + 2;</span><br><span class="line">  &#125; catch (e)&#123;</span><br><span class="line">    console.log(e);</span><br><span class="line">  &#125;</span><br><span class="line">  return y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var g &#x3D; gen(1);</span><br><span class="line">g.next();</span><br><span class="line">g.throw(&#39;出错了&#39;);</span><br><span class="line">&#x2F;&#x2F; 出错了</span><br></pre></td></tr></table></figure>

<p>上面代码的最后一行，Generator 函数体外，使用指针对象的<code>throw</code>方法抛出的错误，可以被函数体内的<code>try...catch</code>代码块捕获。这意味着，出错的代码与处理错误的代码，实现了时间和空间上的分离，这对于异步编程无疑是很重要的。</p>
<p><strong>异步任务的封装****下面看看如何使用 Generator 函数，执行一个真实的异步任务。</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var fetch &#x3D; require(&#39;node-fetch&#39;);</span><br><span class="line"></span><br><span class="line">function* gen()&#123;</span><br><span class="line">  var url &#x3D; &#39;https:&#x2F;&#x2F;api.github.com&#x2F;users&#x2F;github&#39;;</span><br><span class="line">  var result &#x3D; yield fetch(url);</span><br><span class="line">  console.log(result.bio);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>　　上面代码中，Generator 函数封装了一个异步操作，该操作先读取一个远程接口，然后从 JSON 格式的数据解析信息。就像前面说过的，这段代码非常像同步操作，除了加上了<code>yield</code>命令。</p>
<p>　　执行这段代码的方法如下。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var g &#x3D; gen();</span><br><span class="line">var result &#x3D; g.next();</span><br><span class="line"></span><br><span class="line">result.value.then(function(data)&#123;</span><br><span class="line">  return data.json();</span><br><span class="line">&#125;).then(function(data)&#123;</span><br><span class="line">  g.next(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>　　上面代码中，首先执行 Generator 函数，获取遍历器对象，然后使用<code>next</code>方法（第二行），执行异步任务的第一阶段。由于<code>Fetch</code>模块返回的是一个 Promise 对象，因此要用<code>then</code>方法调用下一个<code>next</code>方法。</p>
<p>　　可以看到，虽然 Generator 函数将异步操作表示得很简洁，但是流程管理却不方便（即何时执行第一阶段、何时执行第二阶段）。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">function* gen(x) &#123;</span><br><span class="line">  yield 1;</span><br><span class="line">  yield 2;</span><br><span class="line">  yield 3;</span><br><span class="line">  return 4;</span><br><span class="line">&#125;</span><br><span class="line">var a &#x3D; gen();</span><br><span class="line">console.log(a.next());</span><br><span class="line">console.log(a.next());</span><br><span class="line">console.log(a.next());</span><br><span class="line">console.log(a.next());</span><br></pre></td></tr></table></figure>

<p>　　最终，打印台输出</p>
<p><img src="/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript.assets/1044137-20170831143725077-1955052959.png" alt="img"></p>
<p>即开始调用gen()，并没有真正的调用，而是<strong>返回了一个生成器对象</strong>，a.next()的时候，执行第一个yield，并立刻暂停执行，交出了控制权； 接着，我们就可以去a.next() 开始恢复执行。。。 如此循环往复。　　</p>
<p><strong>每当调用生成器对象的next的方法时，就会运行到下一个yield表达式。 之所以称这里的gen（）为生成器函数，是因为区别如下：</strong></p>
<ul>
<li><strong>普通函数使用function来声明，而生成器函数使用 function * 来声明</strong>。</li>
<li><strong>普通函数使用return来返回值，而生成器函数使用yield来返回值。</strong></li>
<li><strong>普通函数式run to completion模式 ，即一直运行到末尾； 而生成器函数式 run-pause-run 模式， 函数可以在执行过程中暂停一次或者多次。并且暂停期间允许其他代码执行。</strong></li>
</ul>
<h2 id="async-await"><a href="#async-await" class="headerlink" title="async/await"></a>async/await</h2><p>async函数基于Generator又做了几点改进：</p>
<ul>
<li>内置执行器，将Generator函数和自动执行器进一步包装。</li>
<li>语义更清楚，async表示函数中有异步操作，await表示等待着紧跟在后边的表达式的结果。</li>
<li>适用性更广泛，await后面可以跟promise对象和原始类型的值(Generator中不支持)</li>
</ul>
<p>　　很多人都认为这是异步编程的终极解决方案，由此评价就可知道该方法有多优秀了。它基于Promise使用async/await来优化then链的调用,其实也是Generator函数的语法糖。 async 会将其后的函数（函数表达式或 Lambda）的返回值封装成一个 Promise 对象，而 await 会等待这个 Promise 完成，并将其 resolve 的结果返回出来。</p>
<p>　　await得到的就是返回值，其内部已经执行promise中resolve方法，然后将结果返回。使用async/await的方式写回调任务：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">async function dolt()&#123;</span><br><span class="line">    console.time(&#39;dolt&#39;);</span><br><span class="line">    const time1&#x3D;300;</span><br><span class="line">    const time2&#x3D;await step1(time1);</span><br><span class="line">    const time3&#x3D;await step2(time2);</span><br><span class="line">    const result&#x3D;await step3(time3);</span><br><span class="line">    console.log(&#96;result is $&#123;result&#125;&#96;);</span><br><span class="line">    console.timeEnd(&#39;dolt&#39;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">dolt();</span><br></pre></td></tr></table></figure>

<p>　　可以看到，在使用await关键字所在的函数一定要是async关键字修饰的。</p>
<p>　　功能还很新，属于ES7的语法，但使用Babel插件可以很好的转义。另外<strong>await只能用在async函数中，否则会报错</strong></p>
<h1 id="JS的事件执行机制"><a href="#JS的事件执行机制" class="headerlink" title="JS的事件执行机制"></a>JS的事件执行机制</h1><h2 id="一、js的内存模型"><a href="#一、js的内存模型" class="headerlink" title="一、js的内存模型"></a><strong>一、js的内存模型</strong></h2><p><strong><img src="/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript.assets/1760011-20200512143232426-796587478.png" alt="img"></strong></p>
<h2 id=""><a href="#" class="headerlink" title=""></a><strong><img src="/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript.assets/1760011-20200512143348561-1197833870.png" alt="img"></strong></h2><h2 id="二、js代码执行机制："><a href="#二、js代码执行机制：" class="headerlink" title="二、js代码执行机制："></a><strong>二、js代码执行机制：</strong></h2><ul>
<li><h3 id="所有同步任务都在主线程上的栈中执行。"><a href="#所有同步任务都在主线程上的栈中执行。" class="headerlink" title="所有同步任务都在主线程上的栈中执行。"></a>所有同步任务都在主线程上的栈中执行。</h3></li>
<li><h3 id="主线程之外，还存在一个”任务队列”（task-queue）。只要异步任务有了运行结果，就在”任务队列”之中放置一个事件。"><a href="#主线程之外，还存在一个”任务队列”（task-queue）。只要异步任务有了运行结果，就在”任务队列”之中放置一个事件。" class="headerlink" title="主线程之外，还存在一个”任务队列”（task queue）。只要异步任务有了运行结果，就在”任务队列”之中放置一个事件。"></a>主线程之外，还存在一个”任务队列”（task queue）。只要异步任务有了运行结果，就在”任务队列”之中放置一个事件。</h3></li>
<li><h3 id="一旦”栈”中的所有同步任务执行完毕，系统就会读取”任务队列”，选择出需要首先执行的任务（由浏览器决定，并不按序）。"><a href="#一旦”栈”中的所有同步任务执行完毕，系统就会读取”任务队列”，选择出需要首先执行的任务（由浏览器决定，并不按序）。" class="headerlink" title="一旦”栈”中的所有同步任务执行完毕，系统就会读取”任务队列”，选择出需要首先执行的任务（由浏览器决定，并不按序）。"></a>一旦”栈”中的所有同步任务执行完毕，系统就会读取”任务队列”，选择出需要首先执行的任务（由浏览器决定，并不按序）。</h3></li>
</ul>
<h2 id="三、宏任务与微任务："><a href="#三、宏任务与微任务：" class="headerlink" title="三、宏任务与微任务："></a><strong>三、宏任务与微任务：</strong></h2><ol>
<li><h3 id="MacroTask（宏观Task）-setTimeout-setInterval-requestAnimationFrame（请求动画）-I-O"><a href="#MacroTask（宏观Task）-setTimeout-setInterval-requestAnimationFrame（请求动画）-I-O" class="headerlink" title="MacroTask（宏观Task） setTimeout, setInterval, , requestAnimationFrame（请求动画）, I/O"></a>MacroTask（宏观Task） <strong>setTimeout, setInterval</strong>, , requestAnimationFrame（请求动画）, I/O</h3></li>
<li><h3 id="MicroTask（微观任务）-process-nextTick-Promise-Object-observe-MutationObserver"><a href="#MicroTask（微观任务）-process-nextTick-Promise-Object-observe-MutationObserver" class="headerlink" title="MicroTask（微观任务） process.nextTick, Promise, Object.observe, MutationObserver"></a>MicroTask（微观任务） process.nextTick, <strong>Promise</strong>, Object.observe, MutationObserver</h3></li>
<li><h3 id="先同步-再取出第一个宏任务执行-所有的相关微任务总会在下一个宏任务之前全部执行完毕-如果遇见-就-先微后宏"><a href="#先同步-再取出第一个宏任务执行-所有的相关微任务总会在下一个宏任务之前全部执行完毕-如果遇见-就-先微后宏" class="headerlink" title="先同步 再取出第一个宏任务执行 所有的相关微任务总会在下一个宏任务之前全部执行完毕 如果遇见 就 先微后宏"></a><strong>先同步 再取出第一个宏任务执行 所有的相关微任务总会在下一个宏任务之前全部执行完毕 如果遇见 就 先微后宏</strong></h3></li>
</ol>
<h3 id="案例一：（在主线程上添加宏任务）"><a href="#案例一：（在主线程上添加宏任务）" class="headerlink" title="案例一：（在主线程上添加宏任务）"></a><strong>案例一：（在主线程上添加宏任务）</strong></h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line"> <span class="built_in">console</span>.log(<span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">&#125;,<span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">3</span>) <span class="comment">//1 3 2</span></span><br></pre></td></tr></table></figure>

<p>先看代码：一个打印，一个定时器，一个打印</p>
<p>因为<strong>定时器是异步操作，又是宏任务，</strong>所以先执行第一个打印，接着<strong>将setTimeout放入宏任务队列</strong>，接着执行第二个打印，再执行宏任务队列中的setTimeout</p>
<h3 id="案例二：（在主线程上添加微任务）"><a href="#案例二：（在主线程上添加微任务）" class="headerlink" title="案例二：（在主线程上添加微任务）"></a>案例二：（在主线程上添加微任务）</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="number">1</span>)</span><br><span class="line"> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve,reject</span>)</span>&#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="string">'2'</span>)</span><br><span class="line">     resolve()</span><br><span class="line"> &#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="number">3</span>)</span><br><span class="line"> &#125;)</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="number">4</span>)  <span class="comment">//1 2 4 3</span></span><br></pre></td></tr></table></figure>

<p>先看代码：一个打印，一个new promise,一个promise.then，一个打印</p>
<p>因为<strong>new promise会立即执行，promise.then是异步操作且是微任务</strong></p>
<p>所以，先执行第一个打印，执行new Promise，<strong>将promise.then放入微任务队列</strong>，接着执行第二个打印，再执行微任务队列中的promise.then</p>
<h3 id="案例三：（宏任务中创建微任务）"><a href="#案例三：（宏任务中创建微任务）" class="headerlink" title="案例三：（宏任务中创建微任务）"></a>案例三：（宏任务中创建微任务）</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">'1'</span>);</span><br><span class="line"> </span><br><span class="line"> setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">'2'</span>);</span><br><span class="line">   <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="string">'3'</span>);</span><br><span class="line">     resolve();</span><br><span class="line">   &#125;).then(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="string">'4'</span>)</span><br><span class="line">   &#125;)</span><br><span class="line"> &#125;,<span class="number">0</span>)</span><br><span class="line">  </span><br><span class="line"> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">'5'</span>);</span><br><span class="line">   resolve();</span><br><span class="line"> &#125;).then(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">'6'</span>)</span><br><span class="line"> &#125;)</span><br><span class="line"></span><br><span class="line"> setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">'7'</span>);</span><br><span class="line">   <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="string">'8'</span>);</span><br><span class="line">     resolve();</span><br><span class="line">   &#125;).then(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="string">'9'</span>)</span><br><span class="line">   &#125;)</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">'10'</span>)</span><br><span class="line"> &#125;,<span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">'11'</span>)</span><br></pre></td></tr></table></figure>

<p>// 1 5 11 6 2 3 4 7 8 10 9</p>
<p>先看代码：一个打印，第一个定时器，一个new promise,一个promise.then,第二个定时器，一个打印</p>
<p><strong>定时器是异步操作，又是宏任务，*<em>promise.then是异步操作且是微任务*</em></strong></p>
<p><strong>所以，先执行第一个打印（1），将第一个定时器放入宏任务队列，执行new Promise（5），将promise.then放入微任务队列，将第二个定时器放入宏任务队列，执行打印（11）；</strong></p>
<p><strong>主线程上的代码执行完毕后，看是否有微任务？此时：微任务队列中有一个promise.then,执行它（6）；微任务执行完毕看宏任务队列；</strong></p>
<p><strong>此时宏任务队列中两个定时器，延时都是0秒，所以按顺序执行就ok,先执行第一个定时器</strong></p>
<p><strong>第一个定时器中：一个打印，一个mew promise,一个promise.then(微任务)；****（宏任务中包含微任务，一定要将宏任务中的微任务执行完，再去执行下一个宏任务）</strong></p>
<p>先执行打印（2），再执行new promise(3),**再执行promise.then(**4);第一个宏任务执行完，执行第二个宏任务（第二个定时器）</p>
<p><strong>第二个定时器中：一个打印，一个new promise，一个promise.then(微任务),一个打印</strong></p>
<p><strong>先执行第一个打印（7），再执行new promise(8),再执行第二个打印（10），在执行promise.then（9）</strong>　</p>
<h3 id="案例四：（微任务中创建宏任务）"><a href="#案例四：（微任务中创建宏任务）" class="headerlink" title="案例四：（微任务中创建宏任务）"></a><strong>案例四：（微任务中创建宏任务）</strong></h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>) =&gt;</span> &#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">"1"</span>)</span><br><span class="line">   resolve()</span><br><span class="line"> &#125;).then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">"2"</span>)</span><br><span class="line">   setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="string">"3"</span>)</span><br><span class="line">   &#125;,<span class="number">0</span>)</span><br><span class="line"> &#125;)</span><br><span class="line"> setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">"4"</span>)</span><br><span class="line"> &#125;,<span class="number">1000</span>)</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"5"</span>)  <span class="comment">//1 5 2 3 4</span></span><br></pre></td></tr></table></figure>

<p>先看代码：一个new promise,（一个then,一个定时器（0秒）），一个定时器（1秒），一个打印 <strong>微任务中有宏任务，则将宏任务放入宏任务队列任务中</strong></p>
<p>先执行new promise(1),<strong>再将promise.then放入微任务队列，将定时器放入宏任务队列（0秒），将定时器放入宏任务队列（1秒）</strong>，执行打印(5)</p>
<p>接着看微任务队列，执行promise.then(2);微任务队列中都执行完再看宏任务队列</p>
<p>宏任务队列中两个定时器，一个延时0秒，一个延时1秒，所以先执行延时0秒的那个</p>
<p>第一个定时器：执行（3）；</p>
<p>第二个定时器：执行（4）</p>
<h1 id="JS事件执行"><a href="#JS事件执行" class="headerlink" title="JS事件执行"></a>JS事件执行</h1><p>本文是承接<a href="https://www.jianshu.com/p/5b1db8806e80" target="_blank" rel="noopener">Promise</a>来说的，大家都知道，JavaScript脚本是单线程的语言，虽然有H5的Web-Worker加持，但是创建出来的子线程完全受主线程控制，且不得操作DOM，所以还是无法改变JavaScript单线程的本质</p>
<blockquote>
<p>JavaScript是单线程执行的，无法同时执行多段代码。当某一段代码正在执行的时候，所有后续的任务都必须等待，形成一个队列。一旦当前任务执行完毕，再从队列中取出下一个任务，这也常被称为 “阻塞式执行”。所以一次鼠标点击，或是计时器到达时间点，或是Ajax请求完成触发了回调函数，这些事件处理程序或回调函数都不会立即运行，而是立即排队，一旦线程有空闲就执行。假如当前JavaScript线程正在执行一段很耗时的代码，此时发生了一次鼠标点击，那么事件处理程序就被阻塞，用户也无法立即看到反馈，事件处理程序会被放入任务队列，直到前面的代码结束以后才会开始执行。如果代码中设定了一个setTimeout，那么浏览器便会在合适的时间，将代码插入任务队列，如果这个时间设为0，就代表立即插入队列，但不是立即执行，仍然要等待前面代码执行完毕。所以 setTimeout 并不能保证执行的时间，是否及时执行取决于JavaScript 线程是拥挤还是空闲。</p>
</blockquote>
<p>这里就涉及到了执行栈(Stack)和队列任务(Queue Task)的概念，将同步任务都放入主线程的Stack当中，将异步和延时的任务都放入Event Queue里面等待执行，Event Queue即为事件队列，所包含的全是事件，等执行栈为空之后就代表主线程执行完毕，再去Event Queue中读取第一个事件放入主线程，执行完毕再读取第二个…因此形成一个JavaScript的Event Loop(事件循环)，Event Loop就是JavaScript的实现异步的一种方式，也是JavaScript的执行机制。</p>
<p>至于定时器(timer)嘛，因为里面的参数有一个是回调函数，另一个是延时执行的毫秒数，所以他也要放进队列中，而上面的引用部分有个延时0毫秒，它的含义就是立即放入队列，而不是立即放进执行栈执行；JavaScript还有一种函数叫做回调函数，阮一峰大神是这么说的：</p>
<blockquote>
<p>所谓”回调函数”（callback），就是那些会被主线程挂起来的代码。异步任务必须指定回调函数，当主线程开始执行异步任务，就是执行对应的回调函数。</p>
</blockquote>
<p>下面这幅图是从别人那里偷来的(ps:主要这幅图太有说服力度了，不信你看)：</p>
<p>![img](https:////upload-images.jianshu.io/upload_images/8560482-92ec4b6e10c45e30.png?imageMogr2/auto-orient/strip|imageView2/2/w/601/format/webp</p>
<p>nodeJs里面提出了和任务队列有关联的方法<code>process.nextTick(callback)</code>，它的含义是本次循环完毕等到下一次循环开始再执行，也就是在当前执行栈的尾部。</p>
<p>在网上经常看到这样的关键字，从广义上来讲，我们弄明白了同步异步，但是狭义上来说还有两个新的概念，其实这个概念我还真不确定官方是否同意，我是看到<a href="https://links.jianshu.com/go?to=https://juejin.im/post/5a6fd5ce6fb9a01c9406208d" target="_blank" rel="noopener">闹闹不爱闹</a>在掘金中阐明的:</p>
<blockquote>
<ol>
<li>宏任务macro task [ˈmækrəʊ]：当前调用栈中执行的代码成为宏任务。（主代码快，定时器等等）。exp:script（全局任务），setTimeout ，setInterval ，setImmediate ，I/O ，UI rendering</li>
<li>微任务micro task [ˈmaɪkrəʊ]： 当前（此次事件循环中）宏任务执行完，在下一个宏任务开始之前需要执行的任务,可以理解为回调事件。（promise.then，proness.nextTick等等）。exp:process.nextTick，promise,Object.observer,MutationObserver</li>
<li>宏任务中的事件放在callback queue中，由事件触发线程维护；微任务的事件放在微任务队列中，由js引擎线程维护。</li>
</ol>
</blockquote>
<p>不管这个东西存不存在，既然国人都这么叫了，那我是这么理解的：<br> 他们口中的宏观任务就是我们的回调函数，宏观任务和微观任务就是我们的Event Queue，执行栈执行完毕会执行微观任务再执行宏观任务，我不建议大家继续这么称呼，其实macro task和micro task都属于是浏览器执行js的执行机制，这个我不是为了较真，估计我也是被我们公司的老总教训的太多了，不去不去怕了怕了o((⊙﹏⊙))o….</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'setTimeout'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">Promise</span>.resolve(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'resolve'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'promise'</span>);</span><br><span class="line">    resolve();</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'then'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'console'</span>);</span><br></pre></td></tr></table></figure>

<p>其实这个栗字很简单，进入script主线程，遇到setTimeout push到macro task，遇到resolve push到macro task，new Promise立即执行，率先打印，then push到micro task，接着第二个打印console，然后执行micro task打印出then，接着执行macro task打印出setTimeout，因为Promise.resolve这个回到函数未调用，有的浏览器报undefined，有的不打印。</p>
<p>到了这里就差不多了，为了帮助大家彻底吃透它，再来一剂猛药：</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">'1'</span>);</span><br><span class="line">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'9'</span>);</span><br><span class="line">    <span class="keyword">this</span>.$nextTick(<span class="function"><span class="params">()</span> =&gt;</span>  &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'11'</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'10'</span>);</span><br><span class="line">        resolve();</span><br><span class="line">    &#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'12'</span>)</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;,<span class="number">5000</span>);</span><br><span class="line"><span class="keyword">this</span>.$nextTick(<span class="function"><span class="params">()</span> =&gt;</span>  &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'3'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'2'</span>);</span><br><span class="line">    resolve();</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'4'</span>);</span><br><span class="line">&#125;);</span><br><span class="line">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'5'</span>);</span><br><span class="line">    <span class="keyword">this</span>.$nextTick(<span class="function"><span class="params">()</span> =&gt;</span>  &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'7'</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'6'</span>);</span><br><span class="line">        resolve();</span><br><span class="line">    &#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'8'</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>看到诸多异步延时任务先不要慌，一步一步来解读，代码中的this.$nextTick(callback)千万不要解读成上面的process.nextTick(callback)，否则你会被坑惨的，process是nodeJs里面的，nodeJs执行机制和JavaScript的执行机制是不同的，nodeJs不会看你代码的层级关系哦，只关心你的事件的类型，按照这个顺序来执行代码，而我们的js是按照父级的事件，有着层级关系的执行。<br> vueJs的主线程先执行，首先打印出1，第一个setTimeout push到macro task，nextTick放入micro task，Promise立即执行，then push进micro task，第二个setTimeout push到macro task，接着执行micro task，打印3 4，最后执行macro task，注意这里有个坑，macro task里面有两个timer，第一个5000ms之后执行，所以先执行第二个，所以最后的答案小学生都知道，打印顺序从1到12。</p>
<h1 id="防抖函数"><a href="#防抖函数" class="headerlink" title="防抖函数"></a>防抖函数</h1><h2 id="一、函数为什么要防抖"><a href="#一、函数为什么要防抖" class="headerlink" title="一、函数为什么要防抖"></a>一、函数为什么要防抖</h2><p>有如下代码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onresize = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'触发窗口监听回调函数'</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当我们在PC上缩放浏览器窗口时，一秒可以轻松触发30次事件。手机端触发其他Dom时间监听回调时同理。</p>
<p>这里的回调函数只是打印字符串，如果回调函数更加复杂，可想而知浏览器的压力会非常大，用户体验会很糟糕。</p>
<p><code>resize</code>或<code>scroll</code>等Dom事件的监听回调会被频繁触发，因此我们要对其进行限制。</p>
<h2 id="二、实现思路"><a href="#二、实现思路" class="headerlink" title="二、实现思路"></a>二、实现思路</h2><p>函数去抖简单来说就是对于一定时间段的连续的函数调用，只让其执行一次，初步的实现思路如下：</p>
<p>第一次调用函数，创建一个定时器，在指定的时间间隔之后运行代码。当第二次调用该函数时，它会清除前一次的定时器并设置另一个。如果前一个定时器已经执行过了，这个操作就没有任何意义。然而，如果前一个定时器尚未执行，其实就是将其替换为一个新的定时器。目的是只有在执行函数的请求停止了一段时间之后才执行。</p>
<h2 id="三、Debounce-应用场景"><a href="#三、Debounce-应用场景" class="headerlink" title="三、Debounce 应用场景"></a>三、Debounce 应用场景</h2><ul>
<li>每次 resize/scroll 触发统计事件</li>
<li>文本输入的验证（连续输入文字后发送 AJAX 请求进行验证，验证一次就好）</li>
</ul>
<h2 id="四、函数防抖最终版"><a href="#四、函数防抖最终版" class="headerlink" title="四、函数防抖最终版"></a>四、函数防抖最终版</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">method, wait, immediate</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> timeout</span><br><span class="line">  <span class="comment">// debounced函数为返回值</span></span><br><span class="line">  <span class="comment">// 使用Async/Await处理异步，如果函数异步执行，等待setTimeout执行完，拿到原函数返回值后将其返回</span></span><br><span class="line">  <span class="comment">// args为返回函数调用时传入的参数，传给method</span></span><br><span class="line">  <span class="keyword">let</span> debounced = <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span> (<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 用于记录原函数执行结果</span></span><br><span class="line">      <span class="keyword">let</span> result</span><br><span class="line">      <span class="comment">// 将method执行时this的指向设为debounce返回的函数被调用时的this指向</span></span><br><span class="line">      <span class="keyword">let</span> context = <span class="keyword">this</span></span><br><span class="line">      <span class="comment">// 如果存在定时器则将其清除</span></span><br><span class="line">      <span class="keyword">if</span> (timeout) &#123;</span><br><span class="line">        clearTimeout(timeout)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 立即执行需要两个条件，一是immediate为true，二是timeout未被赋值或被置为null</span></span><br><span class="line">      <span class="keyword">if</span> (immediate) &#123;</span><br><span class="line">        <span class="comment">// 如果定时器不存在，则立即执行，并设置一个定时器，wait毫秒后将定时器置为null</span></span><br><span class="line">        <span class="comment">// 这样确保立即执行后wait毫秒内不会被再次触发</span></span><br><span class="line">        <span class="keyword">let</span> callNow = !timeout</span><br><span class="line">        timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">          timeout = <span class="literal">null</span></span><br><span class="line">        &#125;, wait)</span><br><span class="line">        <span class="comment">// 如果满足上述两个条件，则立即执行并记录其执行结果</span></span><br><span class="line">        <span class="keyword">if</span> (callNow) &#123;</span><br><span class="line">          result = method.apply(context, args)</span><br><span class="line">          resolve(result)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 如果immediate为false，则等待函数执行并记录其执行结果</span></span><br><span class="line">        <span class="comment">// 并将Promise状态置为fullfilled，以使函数继续执行</span></span><br><span class="line">        timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="comment">// args是一个数组，所以使用fn.apply</span></span><br><span class="line">          <span class="comment">// 也可写作method.call(context, ...args)</span></span><br><span class="line">          result = method.apply(context, args)</span><br><span class="line">          resolve(result)</span><br><span class="line">        &#125;, wait)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 在返回的debounced函数上添加取消方法</span></span><br><span class="line">  debounced.cancel = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    clearTimeout(timeout)</span><br><span class="line">    timeout = <span class="literal">null</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> debounced</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>需要注意的是，如果需要原函数返回值，调用防抖后的函数的外层函数需要使用Async/Await语法等待执行结果返回</p>
<p>使用方法见代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">square</span>(<span class="params">num</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Math</span>.pow(num, <span class="number">2</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> debouncedFn = debounce(square, <span class="number">1000</span>, <span class="literal">false</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'resize'</span>, <span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">let</span> val</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    val = <span class="keyword">await</span> debouncedFn(<span class="number">4</span>)</span><br><span class="line">  &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">    <span class="built_in">console</span>.error(err)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 停止缩放1S后输出：</span></span><br><span class="line">  <span class="comment">// 原函数的返回值为：16</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`原函数返回值为<span class="subst">$&#123;val&#125;</span>`</span>)</span><br><span class="line">&#125;, <span class="literal">false</span>)</span><br></pre></td></tr></table></figure>

<p>具体的实现步骤请往下看</p>
<h2 id="五、Debounce-的实现"><a href="#五、Debounce-的实现" class="headerlink" title="五、Debounce 的实现"></a>五、Debounce 的实现</h2><h3 id="1-《JavaScript高级程序设计》（第三版）中的实现"><a href="#1-《JavaScript高级程序设计》（第三版）中的实现" class="headerlink" title="1. 《JavaScript高级程序设计》（第三版）中的实现"></a>1. 《JavaScript高级程序设计》（第三版）中的实现</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">method, context</span>) </span>&#123;</span><br><span class="line">  clearTimeout(method.tId)</span><br><span class="line">  method.tId = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    method.call(context)</span><br><span class="line">  &#125;, <span class="number">1000</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">print</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'Hello World'</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">window</span>.onresize = debounce(print)</span><br></pre></td></tr></table></figure>

<p>我们不停缩放窗口，当停止1S后，打印出Hello World。</p>
<p><strong>有个可以优化的地方</strong>: 此实现方法有副作用（Side Effect），改变了输入值（method），给method新增了属性</p>
<h3 id="2-优化第一版：消除副作用，将定时器隔离"><a href="#2-优化第一版：消除副作用，将定时器隔离" class="headerlink" title="2. 优化第一版：消除副作用，将定时器隔离"></a>2. 优化第一版：消除副作用，将定时器隔离</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">method, wait, context</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> timeout</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (timeout) &#123;</span><br><span class="line">      clearTimeout(timeout)</span><br><span class="line">    &#125;</span><br><span class="line">    timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      method.call(context)</span><br><span class="line">    &#125;, wait)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-优化第二版：自动调整this正确指向"><a href="#3-优化第二版：自动调整this正确指向" class="headerlink" title="3. 优化第二版：自动调整this正确指向"></a>3. 优化第二版：自动调整this正确指向</h3><p>之前的函数我们需要手动传入函数执行上下文<code>context</code>，现在优化将 this 指向正确的对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">method, wait</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> timeout</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 将method执行时this的指向设为debounce返回的函数被调用时的this指向</span></span><br><span class="line">    <span class="keyword">let</span> context = <span class="keyword">this</span></span><br><span class="line">    <span class="keyword">if</span> (timeout) &#123;</span><br><span class="line">      clearTimeout(timeout)</span><br><span class="line">    &#125;</span><br><span class="line">    timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      method.call(context)</span><br><span class="line">    &#125;, wait)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-优化第三版：函数可传入参数"><a href="#4-优化第三版：函数可传入参数" class="headerlink" title="4. 优化第三版：函数可传入参数"></a>4. 优化第三版：函数可传入参数</h3><p>即便我们的函数不需要传参，但是别忘了JavaScript 在事件处理函数中会提供事件对象 event，所以我们要实现传参功能。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">method, wait</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> timeout</span><br><span class="line">  <span class="comment">// args为返回函数调用时传入的参数，传给method</span></span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> context = <span class="keyword">this</span></span><br><span class="line">    <span class="keyword">if</span> (timeout) &#123;</span><br><span class="line">      clearTimeout(timeout)</span><br><span class="line">    &#125;</span><br><span class="line">    timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// args是一个数组，所以使用fn.apply</span></span><br><span class="line">      <span class="comment">// 也可写作method.call(context, ...args)</span></span><br><span class="line">      method.apply(context, args)</span><br><span class="line">    &#125;, wait)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-优化第四版：提供立即执行选项"><a href="#5-优化第四版：提供立即执行选项" class="headerlink" title="5. 优化第四版：提供立即执行选项"></a>5. 优化第四版：提供立即执行选项</h3><p>有些时候我不希望非要等到事件停止触发后才执行，我希望立刻执行函数，然后等到停止触发n毫秒后，才可以重新触发执行。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">method, wait, immediate</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> timeout</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> context = <span class="keyword">this</span></span><br><span class="line">    <span class="keyword">if</span> (timeout) &#123;</span><br><span class="line">      clearTimeout(timeout)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 立即执行需要两个条件，一是immediate为true，二是timeout未被赋值或被置为null</span></span><br><span class="line">    <span class="keyword">if</span> (immediate) &#123;</span><br><span class="line">      <span class="comment">// 如果定时器不存在，则立即执行，并设置一个定时器，wait毫秒后将定时器置为null</span></span><br><span class="line">      <span class="comment">// 这样确保立即执行后wait毫秒内不会被再次触发</span></span><br><span class="line">      <span class="keyword">let</span> callNow = !timeout</span><br><span class="line">      timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        timeout = <span class="literal">null</span></span><br><span class="line">      &#125;, wait)</span><br><span class="line">      <span class="keyword">if</span> (callNow) &#123;</span><br><span class="line">        method.apply(context, args)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 如果immediate为false，则函数wait毫秒后执行</span></span><br><span class="line">      timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// args是一个类数组对象，所以使用fn.apply</span></span><br><span class="line">        <span class="comment">// 也可写作method.call(context, ...args)</span></span><br><span class="line">        method.apply(context, args)</span><br><span class="line">      &#125;, wait)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="6-优化第五版：提供取消功能"><a href="#6-优化第五版：提供取消功能" class="headerlink" title="6. 优化第五版：提供取消功能"></a>6. 优化第五版：提供取消功能</h3><p>有些时候我们需要在不可触发的这段时间内能够手动取消防抖，代码实现如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">method, wait, immediate</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> timeout</span><br><span class="line">  <span class="comment">// 将返回的匿名函数赋值给debounced，以便在其上添加取消方法</span></span><br><span class="line">  <span class="keyword">let</span> debounced = <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> context = <span class="keyword">this</span></span><br><span class="line">    <span class="keyword">if</span> (timeout) &#123;</span><br><span class="line">      clearTimeout(timeout)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (immediate) &#123;</span><br><span class="line">      <span class="keyword">let</span> callNow = !timeout</span><br><span class="line">      timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        timeout = <span class="literal">null</span></span><br><span class="line">      &#125;, wait)</span><br><span class="line">      <span class="keyword">if</span> (callNow) &#123;</span><br><span class="line">        method.apply(context, args)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        method.apply(context, args)</span><br><span class="line">      &#125;, wait)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 加入取消功能，使用方法如下</span></span><br><span class="line">  <span class="comment">// let myFn = debounce(otherFn)</span></span><br><span class="line">  <span class="comment">// myFn.cancel()</span></span><br><span class="line">  debounced.cancel = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    clearTimeout(timeout)</span><br><span class="line">    timeout = <span class="literal">null</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>至此，我们已经比较完整地实现了一个underscore中的debounce函数。</p>
<h2 id="六、遗留问题"><a href="#六、遗留问题" class="headerlink" title="六、遗留问题"></a>六、遗留问题</h2><p>需要防抖的函数可能是存在返回值的，我们要对这种情况进行处理，<code>underscore</code>的处理方法是将函数返回值在返回的<code>debounced</code>函数内再次返回，但是这样其实是有问题的。如果参数<code>immediate</code>传入值不为<code>true</code>的话，当防抖后的函数第一次被触发时，如果原始函数有返回值，其实是拿不到返回值的，因为原函数是在<code>setTimeout</code>内，是异步延迟执行的，而<code>return</code>是同步执行的，所以返回值是<code>undefined</code>。</p>
<p>第二次触发时拿到的返回值其实是第一次执行的返回值，第三次触发时拿到的返回值其实是第二次执行的返回值，以此类推。</p>
<h3 id="1-使用回调函数处理函数返回值"><a href="#1-使用回调函数处理函数返回值" class="headerlink" title="1. 使用回调函数处理函数返回值"></a>1. 使用回调函数处理函数返回值</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">method, wait, immediate, callback</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> timeout, result</span><br><span class="line">  <span class="keyword">let</span> debounced = <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> context = <span class="keyword">this</span></span><br><span class="line">    <span class="keyword">if</span> (timeout) &#123;</span><br><span class="line">      clearTimeout(timeout)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (immediate) &#123;</span><br><span class="line">      <span class="keyword">let</span> callNow = !timeout</span><br><span class="line">      timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        timeout = <span class="literal">null</span></span><br><span class="line">      &#125;, wait)</span><br><span class="line">      <span class="keyword">if</span> (callNow) &#123;</span><br><span class="line">        result = method.apply(context, args)</span><br><span class="line">        <span class="comment">// 使用回调函数处理函数返回值</span></span><br><span class="line">        callback &amp;&amp; callback(result)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        result = method.apply(context, args)</span><br><span class="line">        <span class="comment">// 使用回调函数处理函数返回值</span></span><br><span class="line">        callback &amp;&amp; callback(result)</span><br><span class="line">      &#125;, wait)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  debounced.cancel = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    clearTimeout(timeout)</span><br><span class="line">    timeout = <span class="literal">null</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> debounced</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样我们就可以在函数防抖时传入一个回调函数来处理函数的返回值，使用代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">square</span>(<span class="params">num</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Math</span>.pow(num, <span class="number">2</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> debouncedFn = debounce(square, <span class="number">1000</span>, <span class="literal">false</span>, val =&gt; &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`原函数的返回值为：<span class="subst">$&#123;val&#125;</span>`</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'resize'</span>, () =&gt; &#123;</span><br><span class="line">  debouncedFn(<span class="number">4</span>)</span><br><span class="line">&#125;, <span class="literal">false</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 停止缩放1S后输出：</span></span><br><span class="line"><span class="comment">// 原函数的返回值为：16</span></span><br></pre></td></tr></table></figure>

<h3 id="2-使用Promise处理返回值"><a href="#2-使用Promise处理返回值" class="headerlink" title="2. 使用Promise处理返回值"></a>2. 使用Promise处理返回值</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">method, wait, immediate</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> timeout, result</span><br><span class="line">  <span class="keyword">let</span> debounced = <span class="function"><span class="keyword">function</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 返回一个Promise，以便可以使用then或者Async/Await语法拿到原函数返回值</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">let</span> context = <span class="keyword">this</span></span><br><span class="line">      <span class="keyword">if</span> (timeout) &#123;</span><br><span class="line">        clearTimeout(timeout)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (immediate) &#123;</span><br><span class="line">        <span class="keyword">let</span> callNow = !timeout</span><br><span class="line">        timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">          timeout = <span class="literal">null</span></span><br><span class="line">        &#125;, wait)</span><br><span class="line">        <span class="keyword">if</span> (callNow) &#123;</span><br><span class="line">          result = method.apply(context, args)</span><br><span class="line">          <span class="comment">// 将原函数的返回值传给resolve</span></span><br><span class="line">          resolve(result)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        timeout = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">          result = method.apply(context, args)</span><br><span class="line">          <span class="comment">// 将原函数的返回值传给resolve</span></span><br><span class="line">          resolve(result)</span><br><span class="line">        &#125;, wait)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  debounced.cancel = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    clearTimeout(timeout)</span><br><span class="line">    timeout = <span class="literal">null</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> debounced</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>使用方法一</strong>：在调用防抖后的函数时，使用<code>then</code>拿到原函数的返回值</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">square</span>(<span class="params">num</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Math</span>.pow(num, <span class="number">2</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> debouncedFn = debounce(square, <span class="number">1000</span>, <span class="literal">false</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'resize'</span>, () =&gt; &#123;</span><br><span class="line">  debouncedFn(<span class="number">4</span>).then(<span class="function"><span class="params">val</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`原函数的返回值为：<span class="subst">$&#123;val&#125;</span>`</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;, <span class="literal">false</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 停止缩放1S后输出：</span></span><br><span class="line"><span class="comment">// 原函数的返回值为：16</span></span><br></pre></td></tr></table></figure>

<p><strong>使用方法二</strong>：调用防抖后的函数的外层函数使用Async/Await语法等待执行结果返回</p>
<p>使用方法见代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">square</span>(<span class="params">num</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Math</span>.pow(num, <span class="number">2</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> debouncedFn = debounce(square, <span class="number">1000</span>, <span class="literal">false</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'resize'</span>, <span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">let</span> val</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    val = <span class="keyword">await</span> debouncedFn(<span class="number">4</span>)</span><br><span class="line">  &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">    <span class="built_in">console</span>.error(err)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`原函数返回值为<span class="subst">$&#123;val&#125;</span>`</span>)</span><br><span class="line">&#125;, <span class="literal">false</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 停止缩放1S后输出：</span></span><br><span class="line"><span class="comment">// 原函数的返回值为：16</span></span><br></pre></td></tr></table></figure>
    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2020/09/06/%E5%AD%A6%E6%A0%A1%E9%A1%B9%E7%9B%AE%E5%BA%94%E7%94%A8/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6JavaScript/" title="深入探究JavaScript">http://example.com/2020/09/06/学校项目应用/深入探究JavaScript/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/" rel="tag"># 面试总结</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/09/06/C++/%E6%B7%B1%E5%85%A5%E6%8E%A2%E7%A9%B6C/" rel="prev" title="深入探究C++">
      <i class="fa fa-chevron-left"></i> 深入探究C++
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/09/07/%E5%89%8D%E7%AB%AF/ES6%E6%96%B0%E5%A2%9E%E6%A0%87%E5%87%86/" rel="next" title="ES6新增标准">
      ES6新增标准 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#JS方法-函数重载的姿势"><span class="nav-number">1.</span> <span class="nav-text">JS方法&#x2F;函数重载的姿势</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#借助流程控制语句"><span class="nav-number">1.1.</span> <span class="nav-text">借助流程控制语句</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#巧用闭包特性"><span class="nav-number">1.2.</span> <span class="nav-text">巧用闭包特性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#巧用引用类型特性"><span class="nav-number">1.3.</span> <span class="nav-text">巧用引用类型特性</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#JS异步操作的方法"><span class="nav-number">2.</span> <span class="nav-text">JS异步操作的方法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#回调函数"><span class="nav-number">2.1.</span> <span class="nav-text">回调函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事件监听"><span class="nav-number">2.2.</span> <span class="nav-text">事件监听</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#发布订阅"><span class="nav-number">2.3.</span> <span class="nav-text">发布订阅</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#promise对象"><span class="nav-number">2.4.</span> <span class="nav-text">promise对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#generator函数的异步应用"><span class="nav-number">2.5.</span> <span class="nav-text">generator函数的异步应用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#async-await"><span class="nav-number">2.6.</span> <span class="nav-text">async&#x2F;await</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#JS的事件执行机制"><span class="nav-number">3.</span> <span class="nav-text">JS的事件执行机制</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、js的内存模型"><span class="nav-number">3.1.</span> <span class="nav-text">一、js的内存模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#"><span class="nav-number">3.2.</span> <span class="nav-text"></span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、js代码执行机制："><span class="nav-number">3.3.</span> <span class="nav-text">二、js代码执行机制：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#所有同步任务都在主线程上的栈中执行。"><span class="nav-number">3.3.1.</span> <span class="nav-text">所有同步任务都在主线程上的栈中执行。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#主线程之外，还存在一个”任务队列”（task-queue）。只要异步任务有了运行结果，就在”任务队列”之中放置一个事件。"><span class="nav-number">3.3.2.</span> <span class="nav-text">主线程之外，还存在一个”任务队列”（task queue）。只要异步任务有了运行结果，就在”任务队列”之中放置一个事件。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一旦”栈”中的所有同步任务执行完毕，系统就会读取”任务队列”，选择出需要首先执行的任务（由浏览器决定，并不按序）。"><span class="nav-number">3.3.3.</span> <span class="nav-text">一旦”栈”中的所有同步任务执行完毕，系统就会读取”任务队列”，选择出需要首先执行的任务（由浏览器决定，并不按序）。</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、宏任务与微任务："><span class="nav-number">3.4.</span> <span class="nav-text">三、宏任务与微任务：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#MacroTask（宏观Task）-setTimeout-setInterval-requestAnimationFrame（请求动画）-I-O"><span class="nav-number">3.4.1.</span> <span class="nav-text">MacroTask（宏观Task） setTimeout, setInterval, , requestAnimationFrame（请求动画）, I&#x2F;O</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MicroTask（微观任务）-process-nextTick-Promise-Object-observe-MutationObserver"><span class="nav-number">3.4.2.</span> <span class="nav-text">MicroTask（微观任务） process.nextTick, Promise, Object.observe, MutationObserver</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#先同步-再取出第一个宏任务执行-所有的相关微任务总会在下一个宏任务之前全部执行完毕-如果遇见-就-先微后宏"><span class="nav-number">3.4.3.</span> <span class="nav-text">先同步 再取出第一个宏任务执行 所有的相关微任务总会在下一个宏任务之前全部执行完毕 如果遇见 就 先微后宏</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#案例一：（在主线程上添加宏任务）"><span class="nav-number">3.4.4.</span> <span class="nav-text">案例一：（在主线程上添加宏任务）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#案例二：（在主线程上添加微任务）"><span class="nav-number">3.4.5.</span> <span class="nav-text">案例二：（在主线程上添加微任务）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#案例三：（宏任务中创建微任务）"><span class="nav-number">3.4.6.</span> <span class="nav-text">案例三：（宏任务中创建微任务）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#案例四：（微任务中创建宏任务）"><span class="nav-number">3.4.7.</span> <span class="nav-text">案例四：（微任务中创建宏任务）</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#JS事件执行"><span class="nav-number">4.</span> <span class="nav-text">JS事件执行</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#防抖函数"><span class="nav-number">5.</span> <span class="nav-text">防抖函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、函数为什么要防抖"><span class="nav-number">5.1.</span> <span class="nav-text">一、函数为什么要防抖</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、实现思路"><span class="nav-number">5.2.</span> <span class="nav-text">二、实现思路</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、Debounce-应用场景"><span class="nav-number">5.3.</span> <span class="nav-text">三、Debounce 应用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、函数防抖最终版"><span class="nav-number">5.4.</span> <span class="nav-text">四、函数防抖最终版</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、Debounce-的实现"><span class="nav-number">5.5.</span> <span class="nav-text">五、Debounce 的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-《JavaScript高级程序设计》（第三版）中的实现"><span class="nav-number">5.5.1.</span> <span class="nav-text">1. 《JavaScript高级程序设计》（第三版）中的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-优化第一版：消除副作用，将定时器隔离"><span class="nav-number">5.5.2.</span> <span class="nav-text">2. 优化第一版：消除副作用，将定时器隔离</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-优化第二版：自动调整this正确指向"><span class="nav-number">5.5.3.</span> <span class="nav-text">3. 优化第二版：自动调整this正确指向</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-优化第三版：函数可传入参数"><span class="nav-number">5.5.4.</span> <span class="nav-text">4. 优化第三版：函数可传入参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-优化第四版：提供立即执行选项"><span class="nav-number">5.5.5.</span> <span class="nav-text">5. 优化第四版：提供立即执行选项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-优化第五版：提供取消功能"><span class="nav-number">5.5.6.</span> <span class="nav-text">6. 优化第五版：提供取消功能</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六、遗留问题"><span class="nav-number">5.6.</span> <span class="nav-text">六、遗留问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-使用回调函数处理函数返回值"><span class="nav-number">5.6.1.</span> <span class="nav-text">1. 使用回调函数处理函数返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-使用Promise处理返回值"><span class="nav-number">5.6.2.</span> <span class="nav-text">2. 使用Promise处理返回值</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

